package net.alan.modules.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.alan.common.constants.EChatType;
import net.alan.common.utils.Base64;
import net.alan.common.utils.IOUtils;
import net.alan.modules.aspect.NotAuthorize;
import net.alan.modules.bean.*;
import net.alan.modules.cache.WebContextUtil;
import net.alan.modules.handle.BaseExecption;
import net.alan.modules.service.IChatService;
import net.alan.modules.service.IProjectService;
import net.alan.modules.service.IUserService;
import net.alan.modules.wx.MessageVO;
import net.alan.modules.wx.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author 李岩飞
 * Email eliyanfei@126.com
 * 2017/11/21
 */
@Api(tags = "聊天管理")
@Controller
@RequestMapping(value = "chat")
public class ChatController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
    @Autowired
    private IChatService chatService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private CustomConfig customConfig;

    @NotAuthorize
    @RequestMapping(value = "chatlog", method = RequestMethod.GET)
    public String chatlog() {
        return "web/layim/chatlog";
    }

    @ApiOperation(value = "获取聊天信息")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public LayIM list() throws Exception {
        User user = WebContextUtil.getCurrentUser().getUser();
        LayIM layIM = new LayIM();
        layIM.data.mine.username = user.getName();
        layIM.data.mine.id = String.valueOf(user.getId());
        layIM.data.mine.sign = user.getSign();
        layIM.data.mine.avatar = "../photo/get/" + user.getId();//照片
        List<Project> projectList = projectService.findProjectByUserId(user.getId());
        int i = 1;
        for (Project project : projectList) {
            LayIM.Friend friend = new LayIM.Friend();
            friend.groupname = project.getName();
            friend.id = i++;
            layIM.data.friend.add(friend);

            List<Chat> chatList = chatService.findChatByUserId(project.getId(), user.getId());
            if (chatList != null) {
                for (Chat chat : chatList) {
                    Map<String, Object> map = new HashMap();
                    User u = userService.getById(User.class, chat.getToUserId());
                    map.put("username", u.getName());
                    map.put("id", String.valueOf(chat.getId()));
                    map.put("avatar", "../photo/get/" + u.getId());
                    map.put("sign", u.getSign());
                    map.put("status", WebContextUtil.onlineMap.containsKey(u.getAccount()) ? "online" : "hide");
                    friend.list.add(map);
                }
            }
        }
        return layIM;
    }

    @ApiOperation(value = "获取未读聊天")
    @RequestMapping(value = "listUnreadChat", method = RequestMethod.GET)
    @ResponseBody
    public List<Chat> listUnreadChat() throws Exception {
        List<Chat> chatList = this.chatService.listUnreadChat(WebContextUtil.getUserId());
        Integer userId = WebContextUtil.getUserId();
        return chatList;
    }

    @ApiOperation(value = "聊天记录")
    @RequestMapping(value = "listchat", method = RequestMethod.GET)
    @ResponseBody
    public PageModel listchat(Integer id, PageModel pageModel) throws Exception {
        Page<ChatItem> page = this.chatService.findChatItemByChatId(id, pageModel);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Integer userId = WebContextUtil.getUserId();
        Chat chat = this.chatService.getById(Chat.class, id);
        try {
            chat.setReaded(false);
            this.chatService.save(Chat.class, chat);
        } catch (BaseExecption baseExecption) {
            baseExecption.printStackTrace();
        }

        User user1 = WebContextUtil.getCurrentUser().getUser();
        User user2 = this.userService.getById(User.class, chat.getToUserId());
        for (ChatItem item : page.getContent()) {
            Map<String, Object> map = new HashMap();
            map.put("username", item.isSender() ? user1.getName() : user2.getName());
            map.put("id", String.valueOf(item.isSender() ? user1.getId() : user2.getId()));
            map.put("avatar", "../photo/get/" + (item.isSender() ? user1.getId() : user2.getId()));
            map.put("timestamp", item.getCreated().getTime());
            map.put("content", item.getContent());
            map.put("mine", (item.isSender()));
            list.add(map);
        }
        return pageModel.toPageModel(page, list);
    }

    /**
     * 图片上传
     */
    @RequestMapping(value = "upload/image", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadImage(Integer id, HttpServletRequest request)
            throws Exception, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        Result result = ResultUtil.error("");
        try {
            String postFix =
                    IOUtils.getPostFix(file.getOriginalFilename());
            String fileName = System.currentTimeMillis() + "." + postFix;
            String filePath = customConfig.getWorkPath() + fileName;
            IOUtils.copyStream(file.getInputStream(), filePath);
            result = ResultUtil.success(new Src("../photo/image/" + Base64.encodeString(fileName)));
        } catch (Exception baseExecption) {
            ResultUtil.error("");
        }
        return result;
    }

    /**
     * 聊天
     */
    @RequestMapping(value = "item", method = RequestMethod.POST)
    @ResponseBody
    public Result chatItem(Integer id, String content)
            throws Exception, IOException {
        try {
            Integer userId = WebContextUtil.getUserId();
            Chat chat = chatService.getById(Chat.class, id);
            chat.setReaded(false);
            chat.setContent(content);
            chatService.save(Chat.class, chat);
            ChatItem chatItem1 = new ChatItem();
            chatItem1.setChatId(chat.getId());
            chatItem1.setContent(content);
            chatItem1.setSender(true);
            chatItem1.setChatType(EChatType.text.name());
            chatService.save(ChatItem.class, chatItem1);

            Chat otherChat = this.chatService.getOtherChat(chat.getProjectId(), chat.getToUserId(), chat.getUserId());

            ChatItem chatItem2 = new ChatItem();
            chatItem2.setChatId(otherChat.getId());
            chatItem2.setContent(content);
            chatItem2.setSender(false);
            chatItem2.setChatType(EChatType.text.name());
            chatService.save(ChatItem.class, chatItem2);
            sendMessage(content, otherChat.getId(), chat.getUserId(), chat.getToUserId());
        } catch (BaseExecption baseExecption) {
            ResultUtil.error("");
        }
        return ResultUtil.success();
    }

    public void sendMessage(String message, Integer chatId, Integer userId, Integer toUserId) {
        ObjectMapper mapper = new ObjectMapper();
        String Json = "";
        MessageVO messageVO = new MessageVO();
        messageVO.setContent(message);
        messageVO.setId(chatId);
        messageVO.setUserId(userId);
        messageVO.setUserName(WebContextUtil.userMap.get(userId));
        try {
            Json = mapper.writeValueAsString(messageVO);
        } catch (Exception ex) {
        }
        String sessionId = session.getId();
        for (WebSocket webSocket : WebSocket.webSockets) {
            try {
                System.out.println(webSocket.userId + "," + userId);
                if (webSocket.userId == toUserId)
                    webSocket.session.getBasicRemote().sendText(Json);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
